package antani.client.pages;

import antani.client.widgets.ArtistItem;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Panel;

public class ArtistsPage extends Page {

	public final static String MODE_ALL = "all";

	Panel artistPanel;

	public String mode = MODE_ALL;

	public ArtistsPage(Panel artistPanel) {
		this.artistPanel = artistPanel;
	}

	public void showArtists() {

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "/query?type=artist" + getUniqueParam());
		try {
			builder.sendRequest("", new RequestCallback() {

				@Override
				public void onResponseReceived(Request request, Response response) {
					String msg = response.getText();
					String[] lines = msg.split("\\n");

					for (String line : lines) {
						String[] entry = line.split(";");
						if (entry[1].length() > 0)
							artistPanel.add(new ArtistItem(entry[0], entry[1]));
					}
				}

				@Override
				public void onError(Request request, Throwable exception) {
					// TODO Auto-generated method stub

				}
			});
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void activate() {
		artistPanel.setVisible(true);
		showArtists();
	}

	@Override
	public void deactivate() {
		artistPanel.clear();
		artistPanel.setVisible(false);
	}

	public void show(String artist) {
		History.newItem("artist=" + artist);
	}
}
